<template>
  <div>
    <el-form ref="updateForm" :model="userData" :rules="userRule" label-width="80px"
             style="width: 600px;margin: 0 40% 0 auto">
      <el-form-item label="用户名">
        {{ userData.username }}
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userData.nickname"/>
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model="userData.phone"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userData.email"/>
      </el-form-item>
      <el-form-item>
        <div style="margin-left: 50%;transform: translateX(-25%)">
          <el-button type="primary" @click="updateConfirm">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "myMessage",
  data() {
    return {
      userData: {
        nickname: "",
        phone: "",
        email: "",
      },
      userRule: {
        nickname: [
          {required: true, message: "请输入昵称", trigger: "blur"},
        ],
        phone: [
          {required: true, message: "请输入手机号码", trigger: "blur"},
          {
            pattern: /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/,
            message: "手机号码格式错误",
            trigger: "blur"
          }
        ],
        email: [
          {pattren: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/, message: "邮箱格式错误", trigger: "blur"}
        ]
      }
    }
  },
  methods: {
    updateConfirm() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          let url = "http://localhost:9999/zx-ums/user/updateData"
          let data = this.qs.stringify(this.userData);
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('userJwt')}}
          ).post(url, data).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 200) {
              this.$message({message: "数据已保存", type: "success"})
              localStorage.setItem("userNickname", this.userData.nickname)
              location.reload()
            } else {
              this.$message({message: jsonResult.message, type: "error"})
            }
          })
        } else {
          this.$message({message: "数据尚未符合要求", type: "error"})
        }
      })
    },
    loadUserData() {
      let url = "http://localhost:9999/zx-ums/user/standard?id=" + localStorage.getItem("userId");
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('userJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.userData = jsonResult;
        }
      })
    }
  },
  mounted() {
    this.loadUserData()
  }
}
</script>

<style scoped>

</style>